import io
from flask import Flask, render_template, request, jsonify, send_file
from flask_cors import CORS
from PIL import Image
import os

from main import TomotaModel  # 确保 main.py 在同一目录下
from common import db, llm

app = Flask(__name__)
CORS(app)

model = TomotaModel.load_model()
llm_client = llm.DeepSeekClient.get_instance()
database = db.Database.get_instance()

# 模拟番茄疾病识别
@app.route('/predict', methods=['POST'])
def predict():
    file = request.files['file']
    conf_threshold = request.form.get('conf_threshold')
    iou_threshold = request.form.get('iou_threshold')
    
    # image = Image.open(io.BytesIO(file.read()))
    # pil_image, text_result = model.predict(image, conf_threshold, iou_threshold)

    
    # 这里可以添加实际的疾病识别逻辑
    result = {
        "image": "path/to/result/image.jpg",
        "label": "健康",
        "confidence": 0.9,
        "suggestion": "继续保持良好的种植条件"
    }
    return jsonify(result)


@app.route('/generate-sql', methods=['POST'])
def generate_sql():
    requirement = request.form.get('requirement')
    print("hellot")
    
    sql = "SELECT * FROM detection WHERE ..."
    return jsonify({"sql": sql})

# 模拟 SQL 查询
@app.route('/execute-sql', methods=['POST'])
def execute_sql():
    data = request.get_json()
    sql = data.get('sql')
    # 这里可以添加实际的 SQL 查询逻辑
    result = "查询结果"
    return jsonify({"result": result})

# 模拟报告生成
@app.route('/generate-report', methods=['POST'])
def generate_report():
    data = request.get_json()
    result = data.get('result')
    # 这里可以添加实际的报告生成逻辑
    report = "数据分析结论：... "
    return jsonify({"report": report})

@app.route('/')
def index():
    return send_file("index.html")

if __name__ == '__main__':
    app.run(debug=True, port=8000)
